package v1

import (
	"gitee.com/buddyxiao/ginblog/model"
	"gitee.com/buddyxiao/ginblog/utils"
	"gitee.com/buddyxiao/ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// AddCategory 添加分类
func AddCategory(ctx *gin.Context) {
	var data model.Category
	_ = ctx.ShouldBindJSON(&data)
	code := model.CheckCategory(data.Name)
	if code == errmsg.SUCCESS {
		model.CreateCategory(&data)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// GetCategories 查询分类列表
func GetCategories(ctx *gin.Context) {
	pageNum, _ := strconv.Atoi(ctx.Query("pageNum"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	// 页码预处理
	utils.CheckPage(&pageNum, &pageSize)
	data, err, total := model.GetCategories(pageNum, pageSize)
	code := errmsg.SUCCESS
	if err != nil {
		code = errmsg.ERROR
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"total":  total,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// 查询某个分类信息
func GetCategory(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	data, code := model.GetCategory(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// EditCategory 编辑分类
func EditCategory(ctx *gin.Context) {
	var data model.Category
	id, _ := strconv.Atoi(ctx.Param("id"))
	_ = ctx.ShouldBindJSON(&data)
	code := model.CheckUpCategory(id, data.Name)
	if code == errmsg.ERROR_CATEGORY_USED {
		ctx.Abort()
	} else { // 分类不存在
		model.EditCategory(id, &data)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// DeleteCategory 删除分类
func DeleteCategory(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	code := model.DeleteCategory(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})

}
